import cv2 as cv
import numpy as np
from PIL import ImageGrab
from pymouse import PyMouse
from pykeyboard import PyKeyboard

# 实例化
m = PyMouse()
k = PyKeyboard()
def template_image(x1,y1,x2,y2,templatePicPath):
    # target = cv.imread(r"I:\pythonSolution\projects\sw4sy\test\imageDeal\wws111.png")
    bbox = (x1, y1, x2, y2)
    target = np.array(ImageGrab.grab(bbox))
    #转灰度图片
    # target = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
    # 读取目标查找图片
    # target = cv.imread(Target, 0)

    tpl = cv.imread(templatePicPath)
    # cv.imshow("modul", tpl)
    # cv.imshow("yuan", target)
    # methods = [cv.TM_SQDIFF_NORMED, cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED]
    methods = [cv.TM_CCOEFF_NORMED]
    #高，宽
    th, tw = tpl.shape[:2]
    for md in methods:
        result = cv.matchTemplate(target, tpl, md)
        min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
        if md == cv.TM_SQDIFF_NORMED:
            tl = min_loc
        else:
            tl = max_loc
        print(f"min:{min_val},Max:{max_val},位置：{tl[0]},{tl[1]}")
        m.move(tl[0],tl[1])
        #计算矩形右下角的点，出现图片的位置x+tw,y+th
        br = (tl[0] + tw, tl[1] + th)
        cv.rectangle(target, tl, br, [0, 0, 0])
        cv.imshow("pipei" + np.str(md), target)


# template_image(0,0, 1375,800,"I:\\pythonSolution\\projects\\sw4sy\\resources\\img\\shimen_todo_button.png")
# template_image(0,0, 1375,800,r"I:\pythonSolution\projects\sw4sy\test\imageDeal\20200214204532.png")
template_image(626, 146, 747, 184,r"I:\pythonSolution\projects\sw4sy\resources\img\task_richeng_page.png")
cv.waitKey(0)
cv.destroyAllWindows()